package cn.ecut.dzy.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @program: juc
 * @description:
 * @author: DingZhenYun
 * @create: 2021-10-18 21:55
 **/
//第一步  创建资源类，定义属性和和操作方法
class LTicket{
    //票数量
    private int number = 30;
    //创建可重入锁
    private final ReentrantLock lock=new ReentrantLock(true);
    //卖票方法
    public void sale(){
        //上锁
        lock.lock();
        try {
            if(number>0){
                System.out.println(Thread.currentThread().getName() + " : 卖出：" + (number--) + " 剩下：" + number);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //解锁
            lock.unlock();
        }
    }
}
public class LSaleTicket {
    //第二步 创建多个线程，调用资源类的操作方法
    //创建三个线程
    public static void main(String[] args) {
        LTicket lTicket=new LTicket();
        new Thread(()->{
            //调用卖票方法
            for (int i = 0; i < 40; i++) {
                lTicket.sale();
            }
        },"a1").start();
        new Thread(()->{
            //调用卖票方法
            for (int i = 0; i < 40; i++) {
                lTicket.sale();
            }
        },"a2").start();
        new Thread(()->{
            //调用卖票方法
            for (int i = 0; i < 40; i++) {
                lTicket.sale();
            }
        },"a3").start();
    }
}
